import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/app/prisma/client';
import { io } from '@/socket';
import { MessageType } from '@/app/types/message';
import getUserId from '@/utils/getUserId';

export async function POST(req: NextRequest) {
  try {
    const senderId = getUserId(req);
    if (!senderId) {
      return NextResponse.json({ error: '请先登录' }, { status: 401 });
    }

    const { 
      conversationId,
      content, 
      type = MessageType.TEXT,
      duration,
    } = await req.json();

    if (!content || !conversationId) {
      return NextResponse.json({ error: '缺少消息内容或会话ID' }, { status: 400 });
    }

    // 统一验证用户是否是会话的参与者
    const participation = await prisma.conversationParticipant.findUnique({
      where: {
        userId_conversationId: {
          userId: senderId,
          conversationId: conversationId,
        },
      },
    });

    if (!participation) {
      return NextResponse.json({ error: '你无权在此会话中发送消息' }, { status: 403 });
    }

    const messageData: any = {
      content,
      type,
      sender: {
        connect: { id: senderId }
      },
      conversation: {
        connect: { id: conversationId }
      }
    };

    // 构建消息
    let newMessage;
    if (type === MessageType.VOICE) {
      if (duration === undefined) {
        return NextResponse.json({ error: '语音消息必须提供时长 (duration)' }, { status: 400 });
      }
      const fileId = content;
      const fileExists = await prisma.file.findUnique({ where: { id: fileId } });
      if (!fileExists) {
        return NextResponse.json({ error: '关联的语音文件不存在' }, { status: 404 });
      }

      newMessage = await prisma.$transaction(async (tx: any) => {
        const msg = await tx.message.create({ data: messageData });
        await tx.voiceMessage.create({
          data: {
            messageId: msg.id,
            url: fileExists.url,
            duration,
            userId: senderId,
          },
        });
        return msg;
      });
    } else {
      // 对于TEXT, IMAGE, FILE等，content直接存储
      newMessage = await prisma.message.create({ data: messageData });
    }

    // WebSocket 推送
    const messageWithDetails = await prisma.message.findUnique({
      where: { id: newMessage!.id },
      include: {
        sender: { select: { id: true, username: true, avatar: true } },
        voice: true, // 如果是语音消息，也一并返回
      },
    });

    const conversation = await prisma.conversation.findUnique({
        where: { id: conversationId },
        include: { participants: { select: { userId: true } } },
    });

    if (conversation) {
        conversation.participants.forEach(member => {
            io.to(member.userId).emit('newMessage', messageWithDetails);
        });
    }

    return NextResponse.json(messageWithDetails, { status: 201 });
  } catch (error) {
    console.error('发送消息失败:', error);
    return NextResponse.json({ error: '服务器错误' }, { status: 500 });
  }
} 